<?php

class Db_Select
{

	static protected $_init = array(
			'select' => '_select',
			'from' => '_from',
			'join' => '_join',
			'where' => '_where',
			'having' => '_having',
			'group' => '_group',
			'limit' => '_limit',
			'offset' => '_offset'
	);
	
	protected $_select = null;

	protected $_from = null;

	protected $_join = null;

	protected $_where = null;

	protected $_limit = null;

	protected $_having = null;

	protected $_group = null;

	/**
	 * @usage:
	 * $sql->select('user as u, name as n')
	 * @param string $cols do not pass array here
	 * @param alias of column
	 */
	public function select($cols, $as = null)
	{
		if ($cols == null)
		{
			$this -> _select = null;
		}
		else
		{
			$this -> _select .= ($this -> _select ? ', ' : '') . ($as ? $cols . ' as ' . $cols : $cols);
		}
		return $this;
	}

	public function from($from, $as = null, $cols = null)
	{

		$from = $as ? $from . ' as ' . $as : $from;

		$this -> _from .= null == $this -> _from ? $from : "\n" . $from;

		if ($cols)
		{
			$this -> select($cols);
		}
		return $this;
	}

	public function where($where)
	{
		$this -> _where .= ($this -> _where ? ',' : '') . $where;
		return $this;
	}

	public function limit($limit)
	{
		$this -> _limit = $limit;
		return $this;
	}

	public function offset($offset)
	{
		$this -> _offset = $offset;
		return $this;
	}

	public function __toString()
	{
		$sql = '';
		
		foreach (self::$_init as $key => $value)
		{
			if (null !== $this -> $value)
			{
				$sql .= "\n " . $key . ' ' . $this -> $value;
			}
		}
		return $sql;
	}

}
